/**
 * Created by zhouli on 18/10/23
 * 针对报表的特殊组件
 * 选择成本中心项组件，组件依赖于账套id
 */
import React from 'react';
import {connect} from 'react-redux';
import {Modal, Input, Icon, Select, Button, Table, Popover, Badge, message} from 'antd';
import {messages} from 'share/common';
import CCService from 'containers/setting/cost-center/cost-center.service';
import 'styles/data-center/report/travel-report/components/cost-center-item-select-for-report/cost-center-item-select-for-report.scss';

const Option = Select.Option;

class CostCenterItemSelectForReport extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      costCenterList: [],
      columns: [

        {
          title: messages('data-center.key28')/*成本中心项名称*/,
          dataIndex: "name",
          width: '40%',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('data-center.key5'/*编码*/),
          dataIndex: "code",
          width: '20%',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('data-center.key6'/*状态*/),
          dataIndex: 'enabled',
          width: '20%',
          render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
                   text={enabled ? messages("common.status.enable") : messages("common.status.disable")}/>)
        },
      ],
      pagination: {
        total: 0,
        page: 0,
        pageSize: 25,//成本中心最多20个，我这边一次性加载
      },
      loading: false,
      data: [],
      rowSelection: {
        type: 'radio',
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      costCenter: {},
      selectedData: [],  //已经选择的数据项
      costCenterItemName: "",//关键字搜索
      costCenterItem: {}//点击确认，需要被返回
    };
  }

  componentDidMount() {
    this.getAllCostCenterList(this.props.setOfBooksId);
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      selectedData: []
    });
    this.getAllCostCenterList(nextProps.setOfBooksId);
  }

  //通过账套id，得到所有成本中心
  getAllCostCenterList(setOfBooksId) {
    if (!setOfBooksId) {
      return;
    }
    let params = {
      page: 0,
      size: 10000,
      setOfBooksId
    };
    this.setState({
      loading: true,
    });
    CCService.getCostCenterBySobId(params)
      .then((response) => {
        this.setState({
          costCenterList: response.data,
          loading: false,
        }, () => {
          if (this.state.costCenterList.length > 0) {
            this.handleChangeCostCenter(this.state.costCenterList[0].costCenterOID);
          } else {
            this.setState({
              data: [],
              costCenter: {}
            })
          }
        })
      });
  }

  //选项改变时的回调，重置selection
  onSelectChange = (selectedRowKeys, selectedRows) => {
    let {rowSelection} = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({rowSelection});
  };
  onSelectItem = (record, selected) => {
    let selectedData = [];
    if (selected) {
      selectedData.push(record);
      this.setState({selectedData});
    }
  };
  handleRowClick = (record) => {
    let costCenterItemOID = record.costCenterItemOID;
    let {rowSelection, selectedData} = this.state;
    if (_hasInArr(costCenterItemOID, rowSelection.selectedRowKeys)) {
      selectedData = [];
      rowSelection.selectedRowKeys = [];
    } else {
      selectedData = [record];
      rowSelection.selectedRowKeys = [costCenterItemOID];
    }
    this.setState({
      selectedData,
      rowSelection
    });

    function _hasInArr(oid, arr) {
      //arr 只有一个元素
      if (arr.length > 1) {
        return arr[0] === oid
      } else {
        return false;
      }
    }
  };
  //查询所有成本中心项通过成本中心oid
  getAllCostCenterItemList = () => {
    const {pagination, costCenter, costCenterItemName} = this.state;
    let costCenterOID = costCenter.costCenterOID;
    let params = {
      page: pagination.page,
      size: pagination.pageSize,
      keyword: costCenterItemName,
      sort: null//是否按照code排序
    };

    if (costCenterOID === undefined) {
      message.warn(messages('data-center.key85')/*没有成本中心，无法搜索成本中心项*/);
      return;
    }
    this.setState({
      loading: true,
    });
    CCService.getCostCenterItemsAll(costCenterOID, params)
      .then((res) => {
        this.setState({
          loading: false,
          data: res.data
        })
      });
  };

  //显示模板
  showModel = () => {
    this.setState({
      visible: true,
      costCenterItemName: "",//关键字搜索
    }, () => {
      this.onChangeCostCenterItemName();
    })
  };
  handleCancel = () => {
    let {rowSelection} = this.state;
    rowSelection.selectedRowKeys = [];
    this.setState({
      selectedData: [],
      rowSelection,
      visible: false
    });
    this.props.onCancel(undefined);
  };
  handleOk = () => {
    this.setState({
      visible: false
    })
    let {rowSelection} = this.state;
    if (rowSelection.selectedRowKeys.length > 0) {
      this.props.onConfirm(rowSelection.selectedRowKeys[0]);
    } else {
      this.props.onConfirm(undefined);
    }
  };
  //搜索成本中心项
  emitEmptyForDep = () => {
    this.userNameInput.focus();
    this.setState({costCenterItemName: ''}, () => {
      this.onChangeCostCenterItemName();
    });
  };
  //查询成本中心项
  handleChangeCostCenter = (value) => {
    let costCenter = this.state.costCenter;
    costCenter.costCenterOID = value;
    this.setState({
      costCenter
    }, () => {
      this.getAllCostCenterItemList();
    })
  }
  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        page: pagination.current - 1,
        pageSize: pagination.pageSize
      }
    }, () => {
      this.getAllCostCenterItemList();
    })
  };
  //搜索成本中心项
  onChangeCostCenterItemName = (e) => {
    let costCenterItemName = "";
    if (e) {
      costCenterItemName = e.target.value;
    }
    this.setState({
      costCenterItemName: costCenterItemName,
    }, () => {
      this.getAllCostCenterItemList();
    });
  };
  onMouseLeaveDepTag = (e) => {
    e.stopPropagation();
  };
  onMouseEnterDepTag = (e) => {
    e.stopPropagation();
  };
  //清除已经选择的成本中心
  onCloseDepTag = (e) => {
    e.stopPropagation();
    let {rowSelection} = this.state;
    rowSelection.selectedRowKeys = [];
    this.setState({
      selectedData: [],
      rowSelection
    }, () => {
      this.props.onCancel(undefined);
    })
  };
  //渲染成本中心选项
  renderOption = (costCenterList) => {
    return costCenterList.map((item) => {
      return <Option value={item.costCenterOID}>{item.name}</Option>
    })
  };


  //渲染值
  renderVauleText = () => {
    let {selectedData} = this.state;
    let {setOfBooksId} = this.props;
    if (setOfBooksId && selectedData.length > 0) {
      return selectedData[0].name;
    } else if (selectedData.length === 0) {
      if (setOfBooksId) {
        return messages('data-center.key27')/*请选择*/;
      } else {
        return messages('data-center.key29')/*请先选择账套*/;
      }
    }
  };
  //渲染值后面的关闭icon class
  renderVauleClass = () => {
    let {selectedData} = this.state;
    let {setOfBooksId} = this.props;
    let class_name1 = "f-right select-dep-close-wrap";
    let class_name2 = "f-right select-dep-close-wrap select-dep-close-wrap-show";
    if (setOfBooksId && selectedData.length > 0) {
      return class_name2;
    } else if (selectedData.length === 0) {
      return class_name1;
    }
  };

  render() {
    let {setOfBooksId, title} = this.props;
    const {
      loading, costCenter, visible, costCenterItemName, costCenterList,
      columns, data, pagination, rowSelection
    } = this.state;
    const suffix = costCenterItemName ? <Icon type="close-circle" onClick={this.emitEmptyForDep}/> : null;
    let inputClassName = !loading && setOfBooksId ? "input" : "input input-disabled";
    return (
      <div className="cost-center-item-select-for-report">
        <div>
          <div className="label-text">
            {title}:
          </div>

          <div className="input-wrap">
            <div className={inputClassName}
                 onClick={!loading && setOfBooksId && this.showModel}>
              {this.renderVauleText()}
            </div>
            <div className={this.renderVauleClass()}
                 onMouseLeave={this.onMouseLeaveDepTag}
                 onMouseEnter={this.onMouseEnterDepTag}
                 onClick={this.onCloseDepTag}>
              <Icon type="close-circle" className="closeCircle"/>
            </div>
          </div>
        </div>

        <Modal
          width={800}
          className="cost-center-select-for-report-modal"
          title={messages('data-center.key27')/*请选择*/ + title}
          closable={false}
          visible={visible}
          footer={[
            <Button key="back"
                    onClick={this.handleCancel}>
              {messages('common.cancel')}
            </Button>,
            <Button key="submit"
                    type="primary"
                    onClick={this.handleOk}>
              {messages('common.ok')}
            </Button>,
          ]}
        >
          <div>
            <div><h3>{messages('data-center.key30')/*成本中心*/}</h3></div>
            <div>
              <Select
                showSearch
                style={{width: 200}}
                placeholder={messages('data-center.key42')/*搜索或选择成本中心*/}
                optionFilterProp="children"
                value={costCenter.costCenterOID}
                onChange={this.handleChangeCostCenter}
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
              >
                {this.renderOption(costCenterList)}
              </Select>
            </div>
            <div>
              <div className="cost-center-item-wrap">
                <div className="table-header-inp f-right">
                  <Input
                    className='cost-center-item-name-search'
                    key={'costCenterItemName-search'}
                    placeholder={messages('data-center.key8'/*输入成本中心项名称或编码*/)}
                    prefix={<Icon type="search" className='font-disabled'/>}
                    suffix={suffix}
                    value={costCenterItemName}
                    onChange={this.onChangeCostCenterItemName}
                    ref={node => this.userNameInput = node}
                  />
                </div>
                <div className="clear"/>
              </div>
              <div className="table-wrap">
                <Table columns={columns}
                       dataSource={data}
                       pagination={pagination}
                       loading={loading}
                       rowKey="costCenterItemOID"
                       bordered
                       onRow={record => ({onClick: () => this.handleRowClick(record)})}
                       rowSelection={rowSelection}
                       onChange={this.onChangePager}
                       size="middle"/>
              </div>
            </div>
          </div>
        </Modal>

      </div>
    );
  }
}

CostCenterItemSelectForReport.propTypes = {
  onConfirm: React.PropTypes.func.isRequired,// 点击确认之后的回调：返回结果
  onCancel: React.PropTypes.func.isRequired,//点击取消的时候
  title: React.PropTypes.any.isRequired,//字段标题
  setOfBooksId: React.PropTypes.any,//账套id，需要有账套id查询成本中心
};

CostCenterItemSelectForReport.defaultProps = {
  title: "成本中心项",//由外面传入
  setOfBooksId: null,
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    tenantMode: state.main.tenantMode,
    company: state.login.company,
  }
}

export default connect(mapStateToProps)(CostCenterItemSelectForReport);



